import json
import os

class Config:
    """管理应用程序配置。"""
    
    DEFAULT_CONFIG = {
        'default_algorithm': 'AES-256',
        'default_mode': 'CBC',
        'recent_files': [],
        'max_recent_files': 10,
        'key_file': 'keys.json',
        'theme': 'light'
    }
    
    def __init__(self, config_file='config.json'):
        self.config_file = config_file
        self.config = self._load_config()
    
    def _load_config(self):
        """从文件加载配置或创建默认配置。"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r') as f:
                    return {**self.DEFAULT_CONFIG, **json.load(f)}
            except:
                return dict(self.DEFAULT_CONFIG)
        return dict(self.DEFAULT_CONFIG)
    
    def save(self):
        """将当前配置保存到文件。"""
        with open(self.config_file, 'w') as f:
            json.dump(self.config, f, indent=2)
    
    def get(self, key, default=None):
        """获取配置值。"""
        return self.config.get(key, default)
    
    def set(self, key, value):
        """设置配置值。"""
        self.config[key] = value
        self.save()
    
    def add_recent_file(self, file_path):
        """添加文件到最近文件列表。"""
        recent = self.config['recent_files']
        if file_path in recent:
            recent.remove(file_path)
        recent.insert(0, file_path)
        self.config['recent_files'] = recent[:self.config['max_recent_files']]
        self.save()